package com.osfw.framework.directive;

import com.osfw.system.entity.dict.SysDictData;
import com.osfw.system.service.dict.ISysDictDataService;
import freemarker.core.Environment;
import freemarker.template.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 字典数据获取指令
 */
@Component
public class DictDirective implements TemplateDirectiveModel {

    @Autowired
    private ISysDictDataService tempdictDataService;
    private static ISysDictDataService dictDataService;

    @PostConstruct
    public void init() {
        dictDataService = this.tempdictDataService;
    }

    @Override
    public void execute(Environment environment, Map map, TemplateModel[] templateModels, TemplateDirectiveBody templateDirectiveBody) throws TemplateException, IOException {
        DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25);
        if (map.containsKey("type") && map.get("type") != null) {
            String type = map.get("type").toString();
            SysDictData dictData = new SysDictData();
            dictData.setDictType(type);
            List<SysDictData> dictList = dictDataService.selectDictDataList(dictData);
            if (map.containsKey("value") && map.get("value") != null) {
                String value = map.get("value").toString();
                String dict = dictDataService.selectDictLabel(type, value);
                if (dict == null) {
                    dict = "";
                }
                environment.setVariable("dict", builder.build().wrap(dict));
            } else {
                environment.setVariable("dictList", builder.build().wrap(dictList));
            }
        }
        if (templateDirectiveBody != null) {
            templateDirectiveBody.render(environment.getOut());
        }
    }
}
